package com.cucn.ingmall.order.config;

import cn.hutool.core.util.ObjectUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author KouChaoJie
 * @since: 2022/1/19 15:44
 */
@Configuration
@Slf4j
public class IngmallFeignConfig {
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            /**
             * 将之前的请求头cookie信息设置到新请求里
             * @param template 新请求
             */
            @Override
            public void apply(RequestTemplate template) {
                log.info("feign远程调用前apply");
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (ObjectUtil.isNotEmpty(requestAttributes)){
                    HttpServletRequest request = requestAttributes.getRequest();
                    template.header("Cookie", request.getHeader("Cookie"));
                }
            }
        };
    }
}
